package cn.tedu.homework.work1;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class JDBCReg {
    public static void main(String[] args) {
        try(Connection connection = DBUtil.getConnection()){
            Scanner scanner = new Scanner(System.in);
            while (true) {
                System.out.println("请输入用户名:");
                String username = scanner.nextLine();

                String sql1 = "select id from userinfo where username=?";
                PreparedStatement ps1 = connection.prepareStatement(sql1);
                ps1.setString(1, username);
                ResultSet resultSet = ps1.executeQuery();
                if (resultSet.next()) {
                    System.out.println("用户名已被占用");
                    continue;
                }
                System.out.println("请输入密码:");
                String password = scanner.nextLine();
                System.out.println("请输入昵称:");
                String nickname = scanner.nextLine();
                System.out.println("请输入年龄:");
                int age = scanner.nextInt();

                String sql2 = "insert into userinfo(username,password,nickname,age) values (?,?,?,?)";
                PreparedStatement ps2 = connection.prepareStatement(sql2);
                ps2.setString(1,username);
                ps2.setString(2,password);
                ps2.setString(3,nickname);
                ps2.setInt(4,age);
                int i = ps2.executeUpdate();
                if (i>0){
                    System.out.println("注册成功");
                    break;
                }else {
                    System.out.println("注册失败");
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
